package com.company.UI;

import com.company.constant.Constant;

import javax.swing.*;
import java.awt.*;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class LoginUI extends JFrame {

    public LoginUI() {
        setTitle("群聊登录");
        setSize(400, 300);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        init();
        setVisible(true);
    }

    private void init() {
        // 主面板，带渐变背景
        JPanel mainPanel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2 = (Graphics2D) g;
                // 这里定义了一个从上到下的渐变，起始色和结束色可自行修改
                GradientPaint gp = new GradientPaint(
                        0, 0, new Color(135, 206, 235),
                        0, getHeight(), new Color(255, 228, 196)
                );
                g2.setPaint(gp);
                g2.fillRect(0, 0, getWidth(), getHeight());
            }
        };
        mainPanel.setLayout(null); // 使用绝对布局，方便自定义坐标
        add(mainPanel);

        // 标题标签
        JLabel titleLabel = new JLabel("欢迎进入群聊", SwingConstants.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        titleLabel.setForeground(Color.WHITE);
        titleLabel.setBounds(0, 30, getWidth(), 30);
        mainPanel.add(titleLabel);

        // 昵称提示标签
        JLabel nameLabel = new JLabel("请输入昵称：");
        nameLabel.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        nameLabel.setForeground(Color.WHITE);
        nameLabel.setBounds(50, 100, 100, 30);
        mainPanel.add(nameLabel);

        // 输入昵称文本框
        JTextField nameField = new JTextField();
        nameField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        nameField.setBounds(150, 100, 180, 30);
        // 设置一个浅色边框或其他效果
        nameField.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1));
        mainPanel.add(nameField);

        // 登录按钮
        JButton loginButton = new JButton("登录");
        loginButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        loginButton.setBounds(150, 150, 80, 30);
        mainPanel.add(loginButton);

        // 为登录按钮创建点击事件
        loginButton.addActionListener(e -> {
            // 获取输入的昵称
            String name = nameField.getText();
            try {
                // 创建 Socket 连接，并发送登录请求
                Socket socket = new Socket(Constant.SERVER_IP, Constant.SERVER_PORT);
                DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
                dos.writeInt(1); // 代表发送的是 登录请求
                dos.writeUTF(name);
                dos.flush();
                new ClientChatUI(socket, name); // 跳转到 聊天界面
                this.dispose(); // 关闭当前窗口
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        });
    }
}
